import React, { Component } from 'react'
import { connect } from "umi"
import { Row, Col, Checkbox, Table, Switch, Input, Space, Button, Popover, Card, Badge, Drawer, message, Form, Cascader, Tag, Select } from "antd"
import styles from "./index.less"
// const data = require("./table.json")
import { PlusOutlined, MinusOutlined, BarsOutlined, EditOutlined } from '@ant-design/icons';
import { getTables } from "../../../../services/crudService.js";
import uid from 'uid';

class index extends Component {
  constructor(props) {
    super(props)

    this.state = {
      add: this.props.method.some(item => item == "Add"),
      edit: this.props.method.some(item => item == "Edit"),
      del: this.props.method.some(item => item == "Del"),
      export: this.props.isExport,
      import: this.props.isImport,
      search: !this.props.table.filter(item => item.isPK != 1).every(item => !item.isSearch),
      idRow: this.props.table.filter(item => item.isPK == 1),
      rtable: this.props.table.filter(item => item.isPK != 1).map(item => {
        if (typeof item.enum == "undefined") {
          return {
            enum: [{
              id: uid(4),
              key: "",
              value: "",
            }],
            ...item,
          }
        }
        return {
          ...item
        }
      }),
      visible: false,
      options: this.props.db.map(item => ({ label: item.name, value: item.name, isLeaf: false })),
      curName: "",
    }
  }
  setVal({ id, text, value }) {
    const rtable = this.state.rtable.map(item => {
      if (id == item.name) {
        return {
          ...item,
          [text]: value,
        }
      }
      else {
        return item;
      }
    })
    this.setState({
      rtable,
    })
    this.triggerChange({ rtable })
  }
  triggerChange(changedValue) {
    if (this.props.onChange) {
      this.props.onChange({
        ...this.state,
        ...this.props.value,
        ...changedValue,
      });
    }
  }
  componentDidMount() {
    if (typeof this.props.value == "undefined") {
      if (this.props.onChange) {
        this.props.onChange({
          ...this.state,
        });
      }
    }
  }
  render() {
    const columns = [
      {
        title: '字段',
        dataIndex: 'name',
        render: (_, row) => {
          return `${row.name}（${row.typeName}）`
        }
      },
      {
        title: '字段中文名',
        dataIndex: 'cName',
        // width: 120,
        render: (_, row) => {
          return <Input allowClear
            onChange={(e) => {
              this.setVal({
                id: row.name,
                text: "description",
                value: e.target.value,
              })
            }} defaultValue={row.description == null ? "" : row.description} />
        }
      },
      {
        title: '列表',
        dataIndex: 'isTable',
        render: (_, row) => <Switch
          onChange={(v) => {
            this.setVal({
              id: row.name,
              text: "isTable",
              value: v,
            })
          }}
          checkedChildren="显示" unCheckedChildren="隐藏" checked={_} />,
      },
      {
        title: '检索',
        dataIndex: 'isSearch',
        render: (_, row) => <Switch
          onChange={(v) => {
            this.setVal({
              id: row.name,
              text: "isSearch",
              value: v,
            })
          }}
          checkedChildren="显示" unCheckedChildren="隐藏" checked={_} />,
      },
      {
        title: '表单',
        dataIndex: 'isForm',
        render: (_, row) => <Switch
          onChange={(v) => {
            this.setVal({
              id: row.name,
              text: "isForm",
              value: v,
            })
          }}
          checkedChildren="显示" unCheckedChildren="隐藏" checked={_} />,
      },
      {
        title: '表单必填',
        dataIndex: 'required',
        render: (_, row) => <Switch
          onChange={(v) => {
            this.setVal({
              id: row.name,
              text: "required",
              value: v,
            })
          }}
          checkedChildren="是" unCheckedChildren="否" checked={_} />,
      },
      {
        title: '更新前置',
        dataIndex: 'isSwitch',
        render: (_, row) => {
          return row.typeName !== "bit" ? `` : <Switch
            onChange={(v) => {
              this.setVal({
                id: row.name,
                text: "isSwitch",
                value: v,
              })
            }}
            checkedChildren="是" unCheckedChildren="否" checked={_} />
        }
      },
      {
        title: '文本控件',
        dataIndex: 'stringType',
        render: (_, row) => row.typeName !== "varchar" ? `` : <Select
          options={[
            { label: "文本框", value: "text" },
            { label: "图片框", value: "img" },
            { label: "文本域", value: "richText" },
          ]}
          onChange={(v) => {
            this.setVal({
              id: row.name,
              text: "stringType",
              value: v,
            })
          }}
          value={_}
        />,
      },
      {
        title: '枚举',
        valueType: 'option',
        render: (_, row) => <Space>
          {row.typeName == "int" || row.typeName == "varchar" ?
            <Popover
              trigger="click"
              content={
                <Card title={`设置"${row.name}"字段枚举值`} size="small" bordered={false}>
                  {row.enum.map((item, index) => {
                    return (
                      <Row key={index} gutter={12} style={{ marginTop: 5 }}>
                        <Col>
                          <Row>
                            <Col>
                              <font>键：</font>
                            </Col>
                            <Col>
                              <Input allowClear size="small" value={item.key}
                                onChange={(e) => {
                                  const rtable = this.state.rtable.map(sitem => {
                                    if (sitem.name == row.name) {
                                      const en = sitem.enum.map(ssitem => {
                                        if (item.id == ssitem.id) {
                                          return {
                                            ...ssitem,
                                            key: e.target.value
                                          }
                                        }
                                        return ssitem
                                      })
                                      return {
                                        ...sitem,
                                        enum: en,
                                      }
                                    }
                                    else {
                                      return sitem
                                    }
                                  })
                                  this.setState({
                                    rtable
                                  })
                                  this.triggerChange({ rtable })
                                }}
                              />
                            </Col>
                          </Row>
                        </Col>
                        <Col>
                          <Row>
                            <Col>
                              <font>值：</font>
                            </Col>
                            <Col>
                              <Input allowClear
                                onChange={(e) => {
                                  const rtable = this.state.rtable.map(sitem => {
                                    if (sitem.name == row.name) {
                                      const en = sitem.enum.map(ssitem => {
                                        if (item.id == ssitem.id) {
                                          return {
                                            ...ssitem,
                                            value: e.target.value
                                          }
                                        }
                                        return ssitem
                                      })
                                      return {
                                        ...sitem,
                                        enum: en,
                                      }
                                    }
                                    else {
                                      return sitem
                                    }
                                  })
                                  this.setState({
                                    rtable
                                  })
                                  this.triggerChange({ rtable })
                                }}
                                size="small" value={item.value} />
                            </Col>
                          </Row>
                        </Col>
                        <Col>
                          {index == 0 ?
                            <Button size="small" icon={<PlusOutlined />}
                              onClick={() => {
                                const rtable = this.state.rtable.map(sitem => {
                                  if (sitem.name == row.name) {
                                    return {
                                      ...sitem,
                                      enum: [
                                        ...sitem.enum,
                                        { id: uid(4), key: "", value: "" }
                                      ],
                                    }
                                  }
                                  else {
                                    return sitem
                                  }
                                })
                                this.setState({
                                  rtable
                                })
                                this.triggerChange({ rtable })
                              }}
                            />
                            :
                            <Button size="small" icon={<MinusOutlined />}
                              onClick={() => {
                                const rtable = this.state.rtable.map(sitem => {
                                  if (sitem.name == row.name) {
                                    return {
                                      ...sitem,
                                      enum: sitem.enum.filter(ssitem => item.id != ssitem.id),
                                    }
                                  }
                                  else {
                                    return sitem
                                  }
                                })
                                this.setState({
                                  rtable
                                })
                                this.triggerChange({ rtable })
                              }}
                            />
                          }

                        </Col>
                      </Row>
                    )
                  })}
                </Card>
              }
            >
              <Badge count={row.enum.filter(item => !Object.values(item).some(sitem => sitem == "")).length}>
                {/* <DatabaseFilled style={{ fontSize: 20 }} /> */}
                <Button style={{ cursor: "pointer" }} size="small"><BarsOutlined /></Button>
              </Badge>
            </Popover>
            :
            null
          }

        </Space>,
      },
      {
        title: '外联字段',
        render: (_, row) => {
          return row.typeName == "int" ?
            (row["fk"] ?
              <Tag closable onClose={(e) => {
                this.setVal({
                  id: row.name,
                  text: "fk",
                  value: null,
                })
              }}>{row.fk.displayName}</Tag>
              :
              <Button icon={<EditOutlined />} onClick={() => this.setState({ curName: row.name, visible: true })} />)
            : ""

        }
      },
    ];
    return (
      <div className={styles.itemBox}>
        <div className={styles.labelBox}>
          <label>功能选择</label>
        </div>
        <div className={`${styles.controlBox} flag`}>
          <Row gutter={16}>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.add : this.props.value.add}
                onChange={(e) => {
                  this.setState({
                    add: e.target.checked,
                  });
                  this.triggerChange({ add: e.target.checked })
                }}
              >添加</Checkbox>
            </Col>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.edit : this.props.value.edit}
                onChange={(e) => {
                  this.setState({
                    edit: e.target.checked,
                  });
                  this.triggerChange({ edit: e.target.checked })
                }}
              >编辑</Checkbox>
            </Col>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.del : this.props.value.del}
                onChange={(e) => {
                  this.setState({
                    del: e.target.checked,
                  });
                  this.triggerChange({ del: e.target.checked })
                }}
              >删除</Checkbox>
            </Col>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.export : this.props.value.export}
                onChange={(e) => {
                  this.setState({
                    export: e.target.checked,
                  });
                  this.triggerChange({ export: e.target.checked })
                }}
              >导出</Checkbox>
            </Col>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.import : this.props.value.import}
                onChange={(e) => {
                  this.setState({
                    import: e.target.checked,
                  });
                  this.triggerChange({ import: e.target.checked })
                }}
              >导入</Checkbox>
            </Col>
            <Col md={4}>
              <Checkbox
                checked={typeof this.props.value == "undefined" ? this.state.search : this.props.value.search}
                onChange={(e) => {
                  const rtable = e.target.checked ? this.state.rtable.map(item => ({ ...item, isSearch: true })) : this.state.rtable.map(item => ({ ...item, isSearch: false }));
                  this.setState({
                    search: e.target.checked,
                    rtable,
                  });
                  this.triggerChange({ search: e.target.checked, rtable, })
                }}
              >检索</Checkbox>
            </Col>
          </Row>
          <div style={{ height: 20 }}></div>
          <Table
            rowKey={"name"}
            columns={columns}
            dataSource={this.state.rtable}
            pagination={false}
          />
        </div>
        <Drawer
          title="字段外联配置"
          placement="left"
          closable={false}
          onClose={() => this.setState({ visible: false })}
          visible={this.state.visible}
          width={350}
        >
          <Form
            name="cname"
            ref={r => this.myform = r}
            layout="vertical"
            onFinish={async (values) => {
              const arr = (await getTables({ tableName: values.tableName[0] })).filter(item => item.isPK == 1)
              const value = { pkName: arr[0].name, displayName: values.tableName[1], tableName: values.tableName[0], cName: values.cName }
              this.setVal({
                id: this.state.curName,
                text: "fk",
                value,
              })
              this.myform.resetFields()
              this.setState({
                visible: false,
              })

            }}
            onFinishFailed={(errorInfo) => {
              message.error(errorInfo.errorFields[0].errors[0])
            }}
          >
            <Form.Item
              validateTrigger="onSubmit"
              label="关联字段"
              name="tableName"
              rules={[{ required: true, message: '请选择关联字段' }]}
            >
              <Cascader
                loadData={async (selectedOptions) => {
                  const targetOption = selectedOptions[selectedOptions.length - 1];
                  targetOption.loading = true;
                  getTables({ tableName: targetOption.value }).then(arr => {
                    targetOption.loading = false;
                    targetOption.children = arr.map(item => ({
                      label: `${item.name}（${item.typeName}）`,
                      value: item.name,
                    }));
                    this.setState({
                      options: [...this.state.options],
                    });
                  })
                }}
                changeOnSelect={false}
                options={this.state.options}
              />
            </Form.Item>
            <Form.Item
              validateTrigger="onSubmit"
              label="字段中文名"
              name="cName"
              rules={[{ required: true, message: '请填写字段中文名' }]}
            >
              <Input allowClear />
            </Form.Item>
            <Form.Item>
              <Button type="primary" onClick={() => {
                this.myform.submit()
              }} >确定</Button>
            </Form.Item>
          </Form>
        </Drawer>
      </div>
    )
  }
}
export default connect(({ crud: { db } }) => ({ db }))(index)
